package main

import (
	"bufio"
	"fmt"
	"github.com/gookit/color"
	"io/fs"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"
	"strings"
	"sync"
)

var re = regexp.MustCompile(` v.+`)

func RunUpdate(ch int, mod bool, deps map[string][]string) {
	for s, i := range deps {
		color.Yellowln("-->current-->:", s)
		runUpdate(ch, mod, filepath.Dir(s), i)
	}
}
func runUpdate(ch int, mod bool, dir string, deps []string) {
	var wg sync.WaitGroup
	anies := make(chan any, ch)
	for _, i := range deps {
		wg.Add(1)
		anies <- 1
		go func(dep string) {
			defer func() {
				<-anies
				wg.Done()
			}()
			command := exec.Command("go", "get", dep)
			command.Dir = dir
			str := command.String()

			output, err := command.CombinedOutput()
			if err != nil {
				color.Redln(str, "-->err:", err)
				return
			}
			color.Greenln(str, "==>success:", string(output))
		}(i)
	}
	wg.Wait()
	if mod {
		command := exec.Command("go", "mod", "tidy")
		str := command.String()
		output, err := command.CombinedOutput()
		if err != nil {
			color.Redln(str, "->err:", err)
			return
		}
		color.Greenln(str, "=>success:", string(output))
	}
}
func ReadModFile(dir []string) map[string][]string {
	m := make(map[string][]string, 10)
	for _, s := range dir {
		fmt.Println(s)
		open, err := os.Open(s)
		if err != nil {
			fmt.Println(s, err)
			continue
		}
		scanner := bufio.NewScanner(open)
		scanner.Split(bufio.ScanLines)
		for scanner.Scan() {
			text := scanner.Text()
			if re.MatchString(text) {
				allString := strings.TrimSpace(re.ReplaceAllString(text, ""))
				if _, ok := m[s]; ok {
					m[s] = append(m[s], allString)
				} else {
					m[s] = []string{allString}
				}
			}
		}
		open.Close()
	}
	return m
}
func GetModFiles(dir string) []string {
	data := make([]string, 0, 2<<3)
	filepath.Walk(dir, func(path string, info fs.FileInfo, err error) error {
		if info.IsDir() {
			return nil
		}
		if filepath.Ext(path) == ".mod" {
			data = append(data, path)
		}
		return nil
	})
	return data

}
